<template>
  <div class="teacher-dashboard">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>班级学情分析</span>
        </div>
      </template>

      <el-select
        v-model="selectedClassId"
        filterable
        placeholder="请选择要分析的班级"
        style="width: 300px; margin-bottom: 20px"
        @change="fetchAnalytics"
      >
        <el-option
          v-for="item in classList"
          :key="item.classId"
          :label="item.className"
          :value="item.classId"
        />
      </el-select>

      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="analyticsData" class="analytics-content">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-statistic :value="analyticsData.totalStudents" title="班级总人数" />
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>作业平均分趋势</template>
              <v-chart :option="assignmentChartOption" autoresize class="chart" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>高频错题 Top 5</template>
              <el-table :data="analyticsData.commonErrorQuestions" stripe>
                <el-table-column type="index" width="50" />
                <el-table-column label="题目内容" prop="content">
                  <template #default="{ row }">
                    <div class="markdown-content" v-html="renderMarkdown(row.content)" />
                  </template>
                </el-table-column>
                <el-table-column label="错误次数" prop="errorCount" width="100" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-empty v-else description="请选择一个班级以查看学情分析报告" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import VChart from 'vue-echarts'
import { renderMarkdown } from '@/api/utils.ts'

// --- 响应式数据 ---
const classList = ref<any[]>([])
const selectedClassId = ref<number | null>(null)
const analyticsData = ref<any>(null)
const loading = ref(false)

// --- ECharts 图表配置 ---
const assignmentChartOption = computed(() => {
  if (!analyticsData.value?.assignmentStats) {
    return {}
  }
  const stats = [...analyticsData.value.assignmentStats].reverse() // ECharts x轴是从左到右，所以反转数组
  return {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: stats.map((item: any) => item.title),
    },
    yAxis: { type: 'value', name: '平均分' },
    series: [
      {
        data: stats.map((item: any) => item.averageScore.toFixed(2)),
        type: 'line',
        smooth: true,
      },
    ],
  }
})

const fetchMyClasses = async () => {
  try {
    const response = await apiClient.get('/classes/my-classes')
    classList.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取班级列表失败')
  }
}

const fetchAnalytics = async () => {
  if (!selectedClassId.value) return
  loading.value = true
  analyticsData.value = null
  try {
    const response = await apiClient.get(`/teacher/classes/${selectedClassId.value}/analytics`)
    analyticsData.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取学情分析数据失败')
  } finally {
    loading.value = false
  }
}

// --- 生命周期钩子 ---
onMounted(() => {
  fetchMyClasses()
})
</script>

<style scoped>
.teacher-dashboard {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.chart {
  height: 400px;
}
</style>
